// pages/index/index.js
const baiduAIService = require('../../services/baiduAI.js');

Page({
  data: {
    currentPage: 'main', // main, camera, loading, result
    currentTab: 'home',
    showErrorModal: false,
    
    // 加载页面数据
    progress: 0,
    loadingText: 'AI 正在识别您的食物，请稍候',
    loadingTexts: [
      'AI 正在识别您的食物，请稍候',
      '正在计算热量...',
      '分析营养成分中...',
      '即将完成，请稍候...'
    ],
    
    // 结果页面数据
    currentTime: '',
    totalCalories: 450,
    exerciseMinutes: 60,
    nutritionData: {
      protein: 25,
      fat: 30,
      carb: 45
    },
    foodList: [
      {
        name: '米饭',
        weight: 200,
        minWeight: 50,
        maxWeight: 300,
        icon: '🍚',
        iconClass: 'rice-icon'
      },
      {
        name: '红烧肉',
        weight: 150,
        minWeight: 50,
        maxWeight: 250,
        icon: '🥩',
        iconClass: 'meat-icon'
      },
      {
        name: '青菜',
        weight: 100,
        minWeight: 50,
        maxWeight: 200,
        icon: '🥬',
        iconClass: 'vegetable-icon'
      }
    ]
  },

  onLoad() {
    console.log('食物热量识别页面加载完成');
    this.updateCurrentTime();
  },

  onShow() {
    // 页面显示时更新当前时间
    this.updateCurrentTime();
  },

  // 更新当前时间
  updateCurrentTime() {
    const now = new Date();
    const timeStr = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
    this.setData({
      currentTime: timeStr
    });
  },

  // 页面导航方法
  openCamera() {
    this.setData({
      currentPage: 'camera'
    });
  },

  backToMain() {
    this.setData({
      currentPage: 'main'
    });
  },

  // 拍摄相关方法
  async chooseFromAlbum() {
    try {
      const { tempFiles } = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['album']
      });
      
      const tempFilePath = tempFiles[0].tempFilePath;
      console.log("选中图片路径：", tempFilePath);
      
      // 开始识别流程
      this.startRecognition(tempFilePath);
      
    } catch (error) {
      console.error('选择图片失败：', error);
      wx.showToast({
        title: '选择图片失败',
        icon: 'error',
        duration: 2000
      });
    }
  },

  async takePhoto() {
    try {
      const { tempFilePath } = await wx.chooseMedia({
        count: 1,
        mediaType: ['image'],
        sourceType: ['camera']
      });
      
      console.log("拍摄图片路径：", tempFilePath);
      
      // 开始识别流程
      this.startRecognition(tempFilePath);
      
    } catch (error) {
      console.error('拍摄失败：', error);
      wx.showToast({
        title: '拍摄失败',
        icon: 'error',
        duration: 2000
      });
    }
  },

  toggleFlash() {
    wx.showToast({
      title: '闪光灯功能待开发',
      icon: 'none',
      duration: 1500
    });
  },

  // 开始识别流程
  async startRecognition(imagePath) {
    this.setData({
      currentPage: 'loading',
      progress: 0,
      loadingText: this.data.loadingTexts[0]
    });

    try {
      // 开始真实的AI识别
      await this.performRealRecognition(imagePath);
    } catch (error) {
      console.error('识别失败:', error);
      // 显示错误弹窗
      this.setData({
        showErrorModal: true
      });
    }
  },

  // 执行真实的AI识别
  async performRealRecognition(imagePath) {
    let progress = 0;
    const progressInterval = setInterval(() => {
      progress += 2;
      
      // 更新进度和文本
      let textIndex = 0;
      if (progress <= 25) textIndex = 0;
      else if (progress <= 50) textIndex = 1;
      else if (progress <= 75) textIndex = 2;
      else textIndex = 3;
      
      this.setData({
        progress: Math.min(progress, 90), // 最多显示90%，留10%给完成
        loadingText: this.data.loadingTexts[textIndex]
      });
    }, 100);

    try {
      // 调用百度AI识别服务
      const result = await baiduAIService.recognizeFood(imagePath);
      
      // 清除进度条
      clearInterval(progressInterval);
      
      // 完成进度条
      this.setData({
        progress: 100,
        loadingText: '识别完成！'
      });
      
      // 更新识别结果
      this.updateRecognitionResult(result);
      
      // 延迟显示结果页面
      setTimeout(() => {
        this.showResult();
      }, 500);
      
    } catch (error) {
      clearInterval(progressInterval);
      throw error;
    }
  },

  // 更新识别结果
  updateRecognitionResult(result) {
    this.setData({
      foodList: result.foodList,
      totalCalories: Math.round(result.totalCalories),
      nutritionData: result.nutritionData,
      exerciseMinutes: Math.round(result.totalCalories / 7.5) // 假设慢跑每分钟消耗7.5卡路里
    });
  },

  // 显示识别结果
  showResult() {
    this.setData({
      currentPage: 'result'
    });
    
    // 绘制营养图表
    this.drawNutritionChart();
  },

  // 绘制营养图表
  drawNutritionChart() {
    const ctx = wx.createCanvasContext('nutritionChart', this);
    const centerX = 48;
    const centerY = 48;
    const radius = 40;
    
    const data = [
      { value: this.data.nutritionData.protein, color: '#22C55E' },
      { value: this.data.nutritionData.fat, color: '#F97316' },
      { value: this.data.nutritionData.carb, color: '#3B82F6' }
    ];
    
    let startAngle = -0.5 * Math.PI;
    data.forEach(segment => {
      const endAngle = startAngle + (segment.value / 100) * (Math.PI * 2);
      
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.arc(centerX, centerY, radius, startAngle, endAngle);
      ctx.closePath();
      
      ctx.setFillStyle(segment.color);
      ctx.fill();
      
      startAngle = endAngle;
    });
    
    // 绘制中心白色圆形
    ctx.beginPath();
    ctx.arc(centerX, centerY, radius * 0.6, 0, Math.PI * 2);
    ctx.setFillStyle('white');
    ctx.fill();
    
    ctx.draw();
  },

  // 食物重量调整
  onWeightChange(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    
    const foodList = this.data.foodList;
    foodList[index].weight = value;
    
    this.setData({
      foodList: foodList
    });
    
    // 重新计算总热量
    this.calculateTotalCalories();
  },

  // 计算总热量
  calculateTotalCalories() {
    const foodList = this.data.foodList;
    let totalCalories = 0;
    let totalProtein = 0;
    let totalFat = 0;
    let totalCarb = 0;
    let totalWeight = 0;

    foodList.forEach(food => {
      const weight = food.weight;
      const calories = food.calories * weight / 100;
      totalCalories += calories;
      totalWeight += weight;
      totalProtein += food.nutrition.protein * weight / 100;
      totalFat += food.nutrition.fat * weight / 100;
      totalCarb += food.nutrition.carb * weight / 100;
    });

    // 计算营养比例
    const totalNutrients = totalProtein + totalFat + totalCarb;
    let nutritionData = { protein: 33, fat: 33, carb: 34 };
    
    if (totalNutrients > 0) {
      nutritionData = {
        protein: Math.round((totalProtein / totalNutrients) * 100),
        fat: Math.round((totalFat / totalNutrients) * 100),
        carb: Math.round((totalCarb / totalNutrients) * 100)
      };
    }

    const exerciseMinutes = Math.round(totalCalories / 7.5); // 假设慢跑每分钟消耗7.5卡路里
    
    this.setData({
      totalCalories: Math.round(totalCalories),
      exerciseMinutes: exerciseMinutes,
      nutritionData: nutritionData
    });
  },

  // 错误处理
  retryRecognition() {
    this.setData({
      showErrorModal: false,
      currentPage: 'camera'
    });
  },

  manualInput() {
    this.setData({
      showErrorModal: false
    });
    // 显示手动输入弹窗
    wx.showModal({
      title: '手动输入食物',
      content: '请输入食物名称',
      editable: true,
      placeholderText: '例如：米饭、苹果、鸡蛋',
      success: (res) => {
        if (res.confirm && res.content) {
          this.handleManualInput(res.content);
        }
      }
    });
  },

  // 处理手动输入
  handleManualInput(foodName) {
    try {
      // 使用百度AI服务获取食物信息
      const foodInfo = baiduAIService.getFoodInfo(foodName);
      
      const foodList = [{
        name: foodName,
        confidence: 100,
        weight: foodInfo.defaultWeight,
        minWeight: foodInfo.minWeight,
        maxWeight: foodInfo.maxWeight,
        icon: foodInfo.icon,
        iconClass: foodInfo.iconClass,
        calories: foodInfo.caloriesPer100g,
        nutrition: foodInfo.nutrition
      }];

      const result = {
        success: true,
        foodList: foodList,
        totalCalories: baiduAIService.calculateTotalCalories(foodList),
        nutritionData: baiduAIService.calculateNutritionData(foodList)
      };

      this.updateRecognitionResult(result);
      this.showResult();
      
      wx.showToast({
        title: '手动输入成功',
        icon: 'success',
        duration: 1500
      });
    } catch (error) {
      console.error('手动输入处理失败:', error);
      wx.showToast({
        title: '输入失败，请重试',
        icon: 'error',
        duration: 1500
      });
    }
  },

  contactService() {
    this.setData({
      showErrorModal: false
    });
    wx.showModal({
      title: '联系客服',
      content: '识别遇到问题？\n\n1. 确保图片清晰，光线充足\n2. 食物完整显示在画面中\n3. 避免反光和阴影\n\n如需帮助，请通过以下方式联系我们：\n微信：FoodAI_Support\n邮箱：support@foodai.com',
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 功能模块导航
  goToHistory() {
    wx.showToast({
      title: '历史记录功能待开发',
      icon: 'none',
      duration: 1500
    });
  },

  goToProfile() {
    wx.showToast({
      title: '个人中心功能待开发',
      icon: 'none',
      duration: 1500
    });
  },

  goToDietRecord() {
    wx.redirectTo({
      url: '/pages/diet-record/diet-record'
    });
  },

  goToNutrition() {
    wx.redirectTo({
      url: '/pages/nutrition/nutrition'
    });
  },

  goToCommunity() {
    wx.redirectTo({
      url: '/pages/community/community'
    });
  },

  // 底部导航
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    
    switch (tab) {
      case 'home':
        this.setData({
          currentPage: 'main'
        });
        break;
      case 'history':
        wx.redirectTo({
          url: '/pages/history/history'
        });
        break;
      case 'plan':
        wx.redirectTo({
          url: '/pages/plan/plan'
        });
        break;
      case 'profile':
        wx.redirectTo({
          url: '/pages/profile/profile'
        });
        break;
      default:
        this.setData({
          currentPage: 'main'
        });
    }
  },

  // 结果页面操作
  addMoreFood() {
    wx.showToast({
      title: '添加食物功能待开发',
      icon: 'none',
      duration: 1500
    });
  },

  saveToDiet() {
    wx.showToast({
      title: '已记录到今日饮食',
      icon: 'success',
      duration: 1500
    });
    
    // 返回主页
    setTimeout(() => {
      this.setData({
        currentPage: 'main'
      });
    }, 1500);
  },

  viewRecommendations() {
    wx.showToast({
      title: '推荐功能待开发',
      icon: 'none',
      duration: 1500
    });
  }
})
